package com.video.video.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.video.common.exception.ServiceException;
import com.video.common.utils.StringUtils;
import com.video.common.utils.uuid.IdUtils;
import com.video.video.domain.DCommissionRecord;
import com.video.video.domain.DGoods;
import com.video.video.domain.DSystemSettings;
import com.video.video.domain.DUser;
import com.video.video.domain.app.dto.AppOrderDto;
import com.video.video.domain.app.dto.DOrderRecordDto;
import com.video.video.domain.dto.HtDOrderRecordDto;
import com.video.video.domain.vo.DOrderQuery;
import com.video.video.service.IDCommissionRecordService;
import com.video.video.service.IDGoodsService;
import com.video.video.service.IDSystemSettingsService;
import com.video.video.service.IDUserService;
import java.math.BigDecimal;
import java.util.List;
import com.video.common.utils.DateUtils;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.video.video.mapper.DOrderRecordMapper;
import com.video.video.domain.DOrderRecord;
import com.video.video.service.IDOrderRecordService;

/**
 * 订单下载记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-27
 */
@Service
public class DOrderRecordServiceImpl implements IDOrderRecordService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private DOrderRecordMapper dOrderRecordMapper;
    @Autowired
    private IDUserService idUserService;
    @Autowired
    private IDGoodsService idGoodsService;
    @Resource
    private IDSystemSettingsService idSystemSettingsService;
    @Autowired
    private IDCommissionRecordService idCommissionRecordService;

    /**
     * 查询订单下载记录
     *
     * @param id 订单下载记录主键
     * @return 订单下载记录
     */
    @Override
    public DOrderRecord selectDOrderRecordById(String id)
    {
        return dOrderRecordMapper.selectDOrderRecordById(id);
    }

  @Override
  public List<HtDOrderRecordDto> selectHtDOrderRecordDtoList(DOrderQuery query) {
    return dOrderRecordMapper.selectHtDOrderRecordDtoList(query);
  }

  /**
     * 查询订单下载记录列表
     *
     * @param dOrderRecord 订单下载记录
     * @return 订单下载记录
     */
    @Override
    public List<DOrderRecord> selectDOrderRecordList(DOrderRecord dOrderRecord)
    {
        return dOrderRecordMapper.selectDOrderRecordList(dOrderRecord);
    }

  @Override
  public List<DOrderRecordDto> selectDOrderRecordDtoList(String userId) {
        return dOrderRecordMapper.selectDOrderRecordDtoList(userId);
  }

  @Override
    public int insertAppOrdery(AppOrderDto orderDto) {
      DUser user= idUserService.selectDUserById(orderDto.getUserId());
      if(user == null){
          throw new ServiceException("会员不存在");
      }

      if(user.getStatus().equals("2")){
        throw new ServiceException("会员已被禁用");
      }
//     if(user.getLevel().equals("4")){
//        throw new ServiceException("会员为代理不能购买视频");
//     }
//     if(user.getLevel().equals("5")){
//        throw new ServiceException("会员为合伙人不能购买视频");
//     }

      DGoods goods= idGoodsService.selectDGoodsById(orderDto.getGoodId());
      if(goods == null){
          throw new ServiceException("商品不存在");
      }

      if(goods.getStatus().equals("2")){
        throw new ServiceException("商品已下架");
      }

//      if(goods.getDownloadFlg().equals("2")){
//            throw new ServiceException("商品已下载");
//      }

      if(StringUtils.isNotBlank(goods.getBuyerId())){
        throw new ServiceException("商品已出售");
      }

      //会员等级：1 一般用户2 VIP用户3 SVIP 4 代理（不优惠） 5 合伙人(不优惠、不返佣)
        List<DSystemSettings> list2 =idSystemSettingsService.selectDSystemSettingsList(new DSystemSettings());
        DSystemSettings settings=list2.get(0);
        BigDecimal rate=new BigDecimal("1");//会员折扣
        String flgcoom="1";//佣金标识
        if(user.getLevel().equals("1")){
            flgcoom="2";
        }else if(user.getLevel().equals("2")){
            rate=settings.getVipRate();
            flgcoom="2";
        }else if(user.getLevel().equals("3")){
            rate=settings.getSvipRate();
            flgcoom="2";
        }else if(user.getLevel().equals("4")){
            flgcoom="2";
        }

        //判断前后台计算金额是否相等
        BigDecimal payAmount=goods.getSellPrice().multiply(rate);
        if(payAmount.compareTo(orderDto.getSellPrice())!=0){
            logger.info("前端金额:" + orderDto.getSellPrice()+"  后端计算金额:"+payAmount);
            throw new ServiceException("前后台计算金额不相等");
        }

        //判断用户钱包是否充足  (余额加上赠送余额 > 需要支付的)
       BigDecimal totalBalance = user.getBalance().add(user.getGiveBalance());
        if(totalBalance.compareTo(payAmount) < 0){
            throw new ServiceException("钱包金额不足,请充值后再次购买");
        }

        //生成订单
        DOrderRecord order=new DOrderRecord();
        String OrderId=IdUtils.getId();
        order.setId(OrderId);
        order.setUid(orderDto.getUserId());
        order.setGid(orderDto.getGoodId());
        order.setGoodName(goods.getGoodName());
        order.setSellPrice(goods.getSellPrice());
        order.setPayAmount(payAmount);//根据用户身份计算实际价格
        order.setUserRate(rate);//会员折扣比例
        order.setCreateTime(DateUtils.getNowDate());
        dOrderRecordMapper.insertDOrderRecord(order);

        //修改商品购买状态（记录购买人）
//        goods.setDownloadFlg("2");
        goods.setBuyerId(order.getUid());
        idGoodsService.updateDGoods(goods);

        //判断用户是否进行返佣
        if(!user.getPid().equals("0")){
            //判断用户上级身份，合伙人不返佣(除了代理能返两级，其他都为一级返佣)
            DUser user2= idUserService.selectDUserById(user.getPid());
            if(user2.getLevel().equals("1") || user2.getLevel().equals("2") || user2.getLevel().equals("3")){
                 if("Y".equals(user2.getIsCommission())){
                   //一级返佣
                   DCommissionRecord commissionRecord=new DCommissionRecord();
                   commissionRecord.setUid(user.getPid());//被返佣会员id
                   commissionRecord.setCoid(orderDto.getUserId());//返佣的会员id
                   commissionRecord.setOid(OrderId);//订单ID
                   commissionRecord.setOrderAmount(order.getPayAmount());//订单金额
                   commissionRecord.setCommissionRate(settings.getOneRate());//佣金比例
                   commissionRecord.setCommissionAmount(order.getPayAmount().multiply(settings.getOneRate()));//返佣金额
                   idCommissionRecordService.insertDCommissionRecord(commissionRecord);

                   //修改返佣用户信息
                   user2.setTotalAmount(user2.getTotalAmount().add(commissionRecord.getCommissionAmount()));
                   user2.setCommissionBalance(user2.getCommissionBalance().add(commissionRecord.getCommissionAmount()));
                   idUserService.updateDUserInfo(user2);
                 }


                //二级返佣
                if(!user2.getPid().equals("0")){
                    DUser user3= idUserService.selectDUserById(user2.getPid());
                    if(user3.getLevel().equals("4") && "Y".equals(user3.getIsCommission())){
                        DCommissionRecord commissionRecord2=new DCommissionRecord();
                        commissionRecord2.setUid(user2.getPid());//被返佣会员id
                        commissionRecord2.setCoid(orderDto.getUserId());//返佣的会员id
                        commissionRecord2.setOid(OrderId);//订单ID
                        commissionRecord2.setOrderAmount(order.getPayAmount());//订单金额
                        commissionRecord2.setCommissionRate(settings.getTwoRate());//佣金比例
                        commissionRecord2.setCommissionAmount(order.getPayAmount().multiply(settings.getTwoRate()));//返佣金额
                        idCommissionRecordService.insertDCommissionRecord(commissionRecord2);

                        //修改返佣用户信息
                        user3.setTotalAmount(user3.getTotalAmount().add(commissionRecord2.getCommissionAmount()));
                        user3.setCommissionBalance(user3.getCommissionBalance().add(commissionRecord2.getCommissionAmount()));
                        idUserService.updateDUserInfo(user3);
                    }
                }
            }
            if(user2.getLevel().equals("4") && "Y".equals(user2.getIsCommission())){
                //如果代理是一级,则只返一级
                DCommissionRecord commissionRecord=new DCommissionRecord();
                commissionRecord.setUid(user.getPid());//被返佣会员id
                commissionRecord.setCoid(orderDto.getUserId());//返佣的会员id
                commissionRecord.setOid(OrderId);//订单ID
                commissionRecord.setOrderAmount(order.getPayAmount());//订单金额
                commissionRecord.setCommissionRate(settings.getOneRate());//佣金比例
                commissionRecord.setCommissionAmount(order.getPayAmount().multiply(settings.getOneRate()));//返佣金额
                idCommissionRecordService.insertDCommissionRecord(commissionRecord);
            }
        }

        //优先扣减会员钱包  会员钱包不足 再扣减 赠送的金额
       if(user.getBalance().compareTo(order.getPayAmount()) >= 0){
           //钱包余额 >= 订单金额
           user.setBalance(user.getBalance().subtract(order.getPayAmount()));
       }else{
           // 钱包余额 < 订单金额
           //如果钱包余额 >0 先全部扣减  再从 赠送金额中扣减
           if(user.getBalance().compareTo(new BigDecimal("0.0")) >0){

               //赠送金额中应该扣减多少
               BigDecimal deductions = order.getPayAmount().subtract(user.getBalance());
               user.setBalance(new BigDecimal("0.00"));
               user.setGiveBalance(user.getGiveBalance().subtract(deductions));
           }else{
               //钱包余额为0 直接扣减赠送金额
               user.setGiveBalance(user.getGiveBalance().subtract(order.getPayAmount()));
           }
       }

        idUserService.updateDUserInfo(user);
        return 1;
    }

    /**
     * 新增订单下载记录
     *
     * @param dOrderRecord 订单下载记录
     * @return 结果
     */
    @Override
    public int insertDOrderRecord(DOrderRecord dOrderRecord)
    {
        dOrderRecord.setId(IdUtils.getId());
        dOrderRecord.setCreateTime(DateUtils.getNowDate());
        return dOrderRecordMapper.insertDOrderRecord(dOrderRecord);
    }

    /**
     * 修改订单下载记录
     *
     * @param dOrderRecord 订单下载记录
     * @return 结果
     */
    @Override
    public int updateDOrderRecord(DOrderRecord dOrderRecord)
    {
        dOrderRecord.setUpdateTime(DateUtils.getNowDate());
        return dOrderRecordMapper.updateDOrderRecord(dOrderRecord);
    }

    /**
     * 批量删除订单下载记录
     *
     * @param ids 需要删除的订单下载记录主键
     * @return 结果
     */
    @Override
    public int deleteDOrderRecordByIds(String[] ids)
    {
        return dOrderRecordMapper.deleteDOrderRecordByIds(ids);
    }

    /**
     * 删除订单下载记录信息
     *
     * @param id 订单下载记录主键
     * @return 结果
     */
    @Override
    public int deleteDOrderRecordById(String id)
    {
        return dOrderRecordMapper.deleteDOrderRecordById(id);
    }
}
